package com.qingke.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.qingke.factory.ConnectionFactory;
import com.qingke.pojo.User;

public class UserOperation implements JDBCOperation {
	private static Connection conn;
	private  PreparedStatement ps;
	private ResultSet rs;
	
	static {
	 conn = ConnectionFactory.getConnection();
	}
	
	@Override
	public  boolean delete(Object obj) {
		User user = null;
		
		if(obj instanceof User){
			 user = (User)obj;
		}
		try {
			ps = conn.prepareStatement("delete from user where id = ?");
			ps.setInt(1, user.getId());
			return !ps.execute();
		} catch (SQLException e) {
			System.out.println("delete failed");
		}
		return false;
	}

	@Override
	public boolean update(Object obj) {
        User user = null;
		
		if(obj instanceof User){
			 user = (User)obj;
		}
		try {
			ps = conn.prepareStatement("update user set name = ?,gender = ?,company = ?,mobilephone = ? where id = ?");
			ps.setString(1, user.getName());
			ps.setBoolean(2, user.isGender());
			ps.setString(3, user.getCompany());
			ps.setString(4, user.getMobilephone());
			ps.setInt(5, user.getId());
			return !ps.execute();
		} catch (SQLException e) {
			System.out.println("update failed");
		}
		return false;
	}

	@Override
	public boolean insert(Object obj) {
        User user = null;
		
		if(obj instanceof User){
			 user = (User)obj;
		}
		try {
			ps = conn.prepareStatement("insert into user (id,name,gender,company,mobile_phone) values(?,?,?,?,?) ");
			ps.setInt(1, user.getId());
			ps.setString(2, user.getName());
			ps.setBoolean(3, user.isGender());
			ps.setString(4, user.getCompany());
			ps.setString(5, user.getMobilephone());
			
			return !ps.execute();
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("insert failed");
		}
		return false;
	}

	@Override
	public ResultSet select(Object obj) {
        User user = null;
		
		if(obj instanceof User){
			 user = (User)obj;
		}
		try {
			ps = conn.prepareStatement("select * from user where id = ?");
			ps.setInt(1, user.getId());
			return ps.executeQuery();
		} catch (SQLException e) {
			System.out.println("select failed");
		}
		return null;
	}
	
	public String selects(){
		try {
			ps = conn.prepareStatement("select ? from user where id = ?");
			ps.setString(1, "company");
			ps.setInt(2, 1);
			rs = ps.executeQuery();
			rs.next();
			String name = rs.getString(1);
			return name;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
